import Axios from 'axios';
import { uuid } from '@/utils/base/index.js';
import { getToken } from '@/utils/auth'
import { toast } from '@/utils/common'
import store from '@/store' // store
// import Toast from "vant/es/toast";
// import "vant/es/toast/style/less";
// import { setLogout } from '@/utils/base/user';
// const CONFIG = require("./config/index.js")

const http = require('http');

var thisLog = ''
var logConfig = ''
var logResponse = ''
// 设备列表
export function getThis3(data) {
	thisLog = data
	return ''
}
export const ResponseCode = {
    SUCCESS: '00000000',
	SUCCESS2: '200',
    PARAMSERR: '00000100',
    NEWLOGIN: '70000001',
    REFRESHTOKEN: '70000002',
    TOKENEXPIRED: '70000003',
    TOKENEXPIREDNEW: '71302030',
    REFRESH_ID: [70110102, 70112106, 70112107, 70114104, 70114616, 70114621, 70116216, 70116221, 70117101],
    REFRESH_CAM: [70110102, 70112106, 70112107, 70114104, 70116101, 70116102],
    REFRESH_LIB: [70111104, 70111103, 70111100, 70112104, 70114105],
    REFRESH_VIDEO: [70108201, 70116401] // 离线视频需要更新
};
const instance = Axios.create({
	httpAgent: new http.Agent({ keepAlive: false})
 }
);
export const ajaxInit = () => {
    const CONFIG = window.config.common;
    const ajaxConfig = CONFIG.ajaxConfig;
	const openSecurity = CONFIG.openSecurity;
    const instance = Axios.create({
        baseURL: openSecurity?'':CONFIG.baseUrl,
		httpAgent: new http.Agent({ keepAlive: false})
    });
    // 自动构造请求头
    instance.interceptors.request.use(config => {
        const CONFIG = window.config.common;
        const openSecurity = CONFIG.openSecurity;
        const debugMode = window.config.common.debugMode;
        config.timeout = ajaxConfig.longTimeOut || 30000;
        config.headers['Accept'] = '*/*'; // 低版本的火狐问题
        if (config.method === 'post' && !config.headers['Content-Type']) {
            config.headers = {
                'Content-Type': 'application/json'
            };
        }
        if (openSecurity) {
            // 重置地址
			
            // if (!config.url?.includes("resourceList")) {
            const originUrl = config.url || '';
            const baseUrl = originUrl.includes('/spsz') ? CONFIG.baseUrl : CONFIG.imgHeadUrl;
            /* const ident = 'yc-' +
                originUrl.substr(originUrl.indexOf(baseUrl) + baseUrl.length, originUrl.length).replace(/\//g, '-'); */
				const ident = 'yc' +
				    originUrl.replace(/\//g, '-');
				
            const resourceList = CONFIG.resourceList || [];
            let resourceInfo = {};
            for (const item of resourceList) {
                if (item.ident === ident) {
                    resourceInfo = item;
                }
            }
            config.url = '' + '/ydjw_service/services/json';
            const originParans = { ...config.data };
            config.data = {
                appid: CONFIG.securityInfo.appId,
                interface: ident,
                interface_type: CONFIG.securityInfo.type,
                username: localStorage.getItem('policeNo') || CONFIG.securityInfo.userName,
                module: resourceInfo.describe,
                parameter: [originParans]
            };
        }
        debugMode && alert('请求参数====>' + JSON.stringify(config));
		var params = {
			url:config.url,
			data:config.data,
		}
		logConfig = JSON.stringify(params)
        // } else {
        let token = getToken();
        const url = config.url ? config.url : '';
        if (url.indexOf('auth/token') !== -1) {
            token = localStorage['refreshToken'];
        }
        if (token) {
            config.headers['X-Authorization'] = 'Bearer ' + token;
        }
        else {
			config.headers['X-Authorization'] = 'Bearer ' + 'token';
        }
        // 唯一标识
        config.headers['traceId'] = uuid();
		//config.headers['Connection'] = "close";
        // }
        // }
        return config;
    });
    // 自动处理响应
    instance.interceptors.response.use((response) => {
        const CONFIG = window.config.common;
        const openSecurity = CONFIG.openSecurity;
        const debugMode = CONFIG.debugMode;
        debugMode && alert('返回参数1====>' + JSON.stringify(response));
        if (openSecurity) {
            const code = response.data.result
                ? (response.data.result && response.data.result.code) || '9999'
                : (response.result && response.result.code) || '9999';
            const message = response.data.result
                ? response.data.result && response.data.result.msg
                : response.result && response.result.msg;
            response.data =
                (response.data.result && response.data.result.data && response.data.result.data[0]) ||
                    (response.result && response.result.data && response.result.data[0]) || (response.result.data&&response.result.data[0].data) ||
                    {};
            if (code === '9999') {
                response.code = '999999999';
                response.message = message;
            }
            debugMode && alert('返回参数2====>' + JSON.stringify(response.data));
			logResponse = JSON.stringify(response.data)
			if(localStorage.getItem("logFlag")==true||localStorage.getItem("logFlag")=='true'){
				thisLog.$r.toast().show('入参：'+logConfig+'\n'+'出参：'+logResponse);
			}
        }
        const data = response.data;
        const status = response.status;
        if (status === 200) {
            // 其他地方登录账号 或 长时间未操作，退出到登录页面
            if (data.code === ResponseCode.NEWLOGIN ||
                data.code === ResponseCode.TOKENEXPIRED ||
                data.code === ResponseCode.TOKENEXPIREDNEW) {
                // setLogout('');
				store.dispatch('LogOut').then(res => {
				  uni.reLaunch({ url: '/pages/login' })
				})
                return response.data;
            }
            else {
				if (openSecurity) {
					return Promise.resolve(response.data)
				}
                return Promise.resolve(response);
            }
        }
        else {
            return Promise.reject(response);
        }
    }, (error) => {
        const debugMode = window.config.common.debugMode;
        debugMode && alert('返回参数3====>' + JSON.stringify(error));
        let response = error.response;
        const request = error.request;
        const message = '请求异常';
        if (response) {
            if (response.data && response.data.message) {
                // Toast.fail(response.data.message);
				toast(response.data.message)
            }
            else {
                // Toast.fail(message);
				toast(message)
            }
        }
        else if (request && request.status === 0) {
            // Toast.fail("服务异常")
        }
        else {
            // Toast.fail(message);
			toast(message)
        }
        if (!response) {
            response = {};
        }
        if (!response.data) {
            response.data = {};
        }
        response.data._messageFlag = true;
        return Promise.resolve(response);
    });
    return instance;
};
